package com.cp.www.ws.listener;

import org.kurento.client.EndOfStreamEvent;
import org.kurento.client.EventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.JsonObject;

public final class StreamListener implements EventListener<EndOfStreamEvent> {

	private WebSocketSession session;

	private final Logger log = LoggerFactory.getLogger(ErrorListener.class);

	public StreamListener(WebSocketSession session) {
		this.session = session;
	}

	@Override
	public void onEvent(EndOfStreamEvent event) {
		if (session == null) {
			return;
		}
		JsonObject response = new JsonObject();
		response.addProperty("id", "playEnd");
		sendMessage(session, response.toString());
	}

	private synchronized void sendMessage(WebSocketSession session, String message) {
		try {
			session.sendMessage(new TextMessage(message));
		} catch (Exception e) {
			log.error("Exception sending message", e.getMessage());
		}
	}

}
